package com.pms.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.exception.RRException;
import com.pms.rpc.IMemberService;
import com.pms.service.*;
import com.pms.controller.BaseController;
import com.pms.util.DaHaoLockUtil;
import com.pms.util.DateUtil;
import com.pms.util.httpUtil.HttpClientUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * @author ASUS_B
 * @since 2017-10-17
 */
@RestController
@RequestMapping("/doorLock")
@Api(value="门和设备查询相关接口",description = "门和设备查询相关接口")
public class DoorLockApiController extends BaseController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private IEntranceDoorService entranceDoorService;
    @Autowired
    private IEstateDoorLockService estateDoorLockService;
    @Autowired
    private IEstateEqFactoryService estateEqFactoryService;
    @Autowired
    private IEstateAgencyService agencyService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IOwnerMemberService ownerMemberService;
    @Autowired
    private IUnitBuildingService unitBuildingService;
    @Autowired
    IEstateDoorCardService estateDoorCardService;
    @Autowired
    IEstateLockCardService estateLockCardService;
    @Autowired
    DaHaoLockUtil daHaoLockUtil;
    @ApiOperation(value = "查询小区中的门")
    @RequestMapping(value = "/readConmunityDoor",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="conmunityId",value="小区id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="unitId",value="单元id",required = false,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="isHaveLock",value="是(1)/否(2)绑定锁,默认查所有",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="doorType",value="门类型:1-大门,2-单元门,3-车库门,默认查所有",required = false,dataType = "int",paramType="form"),
    })
    public  R readConmunityDoor(Long conmunityId,Long unitId,Integer isHaveLock,Integer doorType){
        parameterIsNull(conmunityId,"社区id不能为空");
        if(isHaveLock!=null){
            if(isHaveLock!=1&&isHaveLock!=2){
                isHaveLock = null;
            }
        }
        if(doorType!=null){
            if(doorType<1||doorType>3){
                doorType = null;
            }
        }
        Wrapper<EntranceDoor> doorWp = new EntityWrapper<EntranceDoor>();
        doorWp.eq("community_id",conmunityId);
        if(unitId!=null){
            if(doorType!=null){
                doorWp.eq("door_type",doorType);
                if(doorType!=1){
                    doorWp.eq("unit_id",unitId);
                }
            }
            if(doorType==null){
                doorWp.and("door_type = {0} or unit_id = {1}",1,unitId);
            }
        }
        if(unitId==null){
            if(doorType!=null){
                doorWp.eq("door_type",doorType);
            }
        }
        if(isHaveLock!=null){
            doorWp.eq("is_have_lock",isHaveLock);
        }
        List<EntranceDoor> doorList = entranceDoorService.selectList(doorWp);
        if(doorList!=null){
            doorList = new ArrayList<EntranceDoor>();
        }
        return R.ok().put("data",doorList).putDescription(EntranceDoor.class);
    }
    @ApiOperation(value = "查询锁是否绑定门")
    @RequestMapping(value = "/readLockIsBindDoor",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="eqSn",value="设备序列号",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="factoryCode",value="设备所属厂商编号",required = false,dataType = "string",paramType="form"),
    })
    public R readLockIsBindDoor(String eqSn,String factoryCode){
        parameterIsBlank(eqSn,"设备序列号不能为空");
        eqSn= eqSn.trim();
        Wrapper<EstateDoorLock> doorLockWp= new EntityWrapper<EstateDoorLock>();
        doorLockWp.eq("eq_sn",eqSn);
        if(StringUtils.isNotBlank(factoryCode)){
            doorLockWp.eq("factory_code",factoryCode);
        }
        EstateDoorLock estateDoorLock =estateDoorLockService.selectOne(doorLockWp);
        boolean lockIsBindDoor = false;
        Map<String,Object> returnMap = new HashMap<String,Object>();
        returnMap.put("doorName","");
        returnMap.put("eqSn",eqSn);
        if(StringUtils.isNotBlank(factoryCode)){
            returnMap.put("factoryCode",factoryCode);
        }
        if(StringUtils.isBlank(factoryCode)){
            returnMap.put("factoryCode","");
        }
        returnMap.put("conmunityId","");
        returnMap.put("conmunityName","");
        returnMap.put("doorId","");
        if (estateDoorLock != null) {
            lockIsBindDoor = true;
            returnMap.put("doorName",estateDoorLock.getDoorName());
            returnMap.put("conmunityId",estateDoorLock.getConmunityId());
            returnMap.put("conmunityName",estateDoorLock.getConmunityName());
            returnMap.put("doorId",estateDoorLock.getDoorId());
        }
        returnMap.put("lockIsBindDoor",lockIsBindDoor);
        StringBuilder descStr = new StringBuilder("{lockIsBindDoor:锁是(true)否(false)绑定门,eqSn:设备序列号,factoryCode:设备所属厂商编号,");
        descStr.append("doorName:门名称,doorId:门id,conmunityId:社区id,conmunityName:社区名称");
        descStr.append("},");
        return R.ok().put("data",returnMap).putDescription(descStr.toString());
    }

    @ApiOperation(value = "绑定门锁")
    @RequestMapping(value = "/bindLockToDoor",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="eqSn",value="设备序列号",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="eqName",value="设备名称",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="eqKey",value="设备密钥",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="eqMac",value="设备mac地址",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="eqInputPswd",value="设备按键开门密码",required = false,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="doorId",value="门id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="factoryCode",value="设备所属厂商编号(后台给予)",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="memberId",value="会员id-验证权限",required = true,dataType = "long",paramType="form"),
    })
    public R bindLockToDoor(String eqSn,String eqName,String eqKey,String eqMac,String eqInputPswd
            ,String factoryCode,Long doorId,Long memberId) {
        parameterIsBlank(eqSn,"设备序列号不能为空");
        parameterIsBlank(eqName,"设备名称不能为空");
        parameterIsBlank(eqKey,"设备密钥不能为空");
        parameterIsBlank(eqMac,"设备mac地址不能为空");
        parameterIsNull(doorId,"请选择绑定的门");
        parameterIsBlank(factoryCode,"设备厂商信息不能为空");
        parameterIsNull(memberId,"会员信息不能为空");
        EntranceDoor door = entranceDoorService.selectById(doorId);
        parameterIsNull(door,"未查询到门信息");
        if(door.getIsHaveLock()!=null&&door.getIsHaveLock()==1){
            return R.error(400,"该门已绑定设备");
        }
        EstateEqFactory eqFactory = estateEqFactoryService.selectOne(new EntityWrapper<EstateEqFactory>().eq("factory_code",factoryCode));
        parameterIsNull(eqFactory,"未查询到厂商信息");
        if(eqFactory.getFactoryType()!=1){// 1锁2摄像头
            return R.error(400,"厂商类型错误");
        }
        Wrapper<EstateDoorLock> doorLockWp= new EntityWrapper<EstateDoorLock>();
        doorLockWp.eq("eq_sn",eqSn);
        doorLockWp.eq("factory_code",factoryCode);
        EstateDoorLock estateDoorLock =estateDoorLockService.selectOne(doorLockWp);
        if(estateDoorLock!=null){
            return R.error(400,"该设备已绑定门");
        }
        Wrapper<OwnerMember> omWp =  new EntityWrapper<OwnerMember>().eq("member_id",memberId);
        omWp.eq("community_id",door.getCommunityId());
        omWp.and("(type_ = {0} or type_ = {1})",3,5);
        OwnerMember om =ownerMemberService.selectOne(omWp);
        parameterIsNull(om,"您没有权限");

        EstateDoorLock insertDoorLock = new EstateDoorLock();
        insertDoorLock.setEqSn(eqSn);
        insertDoorLock.setEqInputPswd(eqInputPswd);
        insertDoorLock.setEqKey(eqKey);
        insertDoorLock.setEqMac(eqMac);
        insertDoorLock.setEqName(eqName);
        insertDoorLock.setEqPswd("");//设置设备密码
        insertDoorLock.setPswdValidTime(null);//设置设备密码有效截止时间
        insertDoorLock.setEqTypeFactory(null);
        insertDoorLock.setFactoryCode(factoryCode);
        insertDoorLock.setFactoryServiceUrl(eqFactory.getFactoryServiceUrl());
        if(null==insertDoorLock.getFactoryServiceUrl()){
            insertDoorLock.setFactoryServiceUrl("");
        }
        insertDoorLock.setCreateTime(new Date());
        insertDoorLock.setUnitId(door.getUnitId());
        insertDoorLock.setDoorType(door.getDoorType());
        insertDoorLock.setDoorId(door.getDoorId());
        insertDoorLock.setDoorName(door.getDoorName());
        insertDoorLock.setConmunityId(om.getCommunityId());
        insertDoorLock.setConmunityName(om.getCommunityName());
        insertDoorLock.setAgencyId(om.getAgencyId());
        estateDoorLockService.insert(insertDoorLock);
        EntranceDoor entranceDoor = new EntranceDoor();
        entranceDoor.setIsHaveLock(1);//修改门状态为  已绑定设备
        entranceDoorService.update(entranceDoor,new EntityWrapper<EntranceDoor>().eq("door_id",doorId));
        return R.ok();
    }

    @ApiOperation(value = "解除门锁绑定")
    @RequestMapping(value = "/removeLockToDoor",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="eqSn",value="设备序列号",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="doorId",value="门id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="memberId",value="会员id-验证权限",required = true,dataType = "long",paramType="form"),
    })
    public R removeLockToDoor(String eqSn,Long doorId,Long memberId) {
        parameterIsBlank(eqSn,"设备序列号不能为空");
        parameterIsNull(doorId,"请选择绑定的门");
        parameterIsNull(memberId,"会员信息不能为空");
        Wrapper<EstateDoorLock> doorLockWp= new EntityWrapper<EstateDoorLock>();
        doorLockWp.eq("eq_sn",eqSn);
        doorLockWp.eq("door_id",doorId);
        EstateDoorLock estateDoorLock =estateDoorLockService.selectOne(doorLockWp);
        parameterIsNull(estateDoorLock,"未查询到相关门锁信息");
        Wrapper<OwnerMember> omWp =  new EntityWrapper<OwnerMember>().eq("member_id",memberId);
        omWp.eq("community_id",estateDoorLock.getConmunityId());
        omWp.and("(type_ = {0} or type_ = {1})",3,5);
        OwnerMember om =ownerMemberService.selectOne(omWp);
        parameterIsNull(om,"您没有权限");
        estateDoorLockService.deleteById(estateDoorLock.getLockId());
        EntranceDoor entranceDoor = new EntranceDoor();
        entranceDoor.setIsHaveLock(2);//修改门状态为  未绑定设备
        entranceDoorService.update(entranceDoor,new EntityWrapper<EntranceDoor>().eq("door_id",doorId));
        // 同步删除 设备的卡片下发记录
        estateDoorCardService.delete(new EntityWrapper<EstateDoorCard>().eq("door_id",doorId));
        estateLockCardService.delete(new EntityWrapper<EstateLockCard>().eq("door_id",doorId));
        return R.ok();
    }

    @ApiOperation(value = "修改门锁按键开门密码")
    @RequestMapping(value = "/editLockInputPswd",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="eqSn",value="设备序列号",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="doorId",value="门id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="memberId",value="会员id-验证权限",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="eqInputPswd",value="设备按键开门密码",required = true,dataType = "string",paramType="form"),
    })
    public R editLockInputPswd(String eqSn,Long doorId,Long memberId,String eqInputPswd) {
        if(StringUtils.isBlank(eqInputPswd)){
            return R.error(400,"请输入按键开门密码");
        }
        parameterIsBlank(eqSn,"设备序列号不能为空");
        parameterIsNull(doorId,"请选择绑定的门");
        parameterIsNull(memberId,"会员信息不能为空");
        Wrapper<EstateDoorLock> doorLockWp= new EntityWrapper<EstateDoorLock>();
        doorLockWp.eq("eq_sn",eqSn);
        doorLockWp.eq("door_id",doorId);
        EstateDoorLock estateDoorLock =estateDoorLockService.selectOne(doorLockWp);
        parameterIsNull(estateDoorLock,"未查询到相关门锁信息");
        Wrapper<OwnerMember> omWp =  new EntityWrapper<OwnerMember>().eq("member_id",memberId);
        omWp.eq("community_id",estateDoorLock.getConmunityId());
        omWp.and("(type_ = {0} or type_ = {1})",3,5);
        OwnerMember om =ownerMemberService.selectOne(omWp);
        parameterIsNull(om,"您没有权限");
        boolean updateTag = false;
        if(StringUtils.isNotBlank(eqInputPswd)){
            eqInputPswd= eqInputPswd.trim();
            if(!eqInputPswd.equals(estateDoorLock.getEqInputPswd())){
                estateDoorLock.setEqInputPswd(eqInputPswd);
                updateTag= true;
            }
        }
        if(updateTag){
            estateDoorLockService.updateById(estateDoorLock);
        }
        return R.ok();
    }

    @ApiOperation(value = "查询厂商设备对应的服务地址")
    @RequestMapping(value = "/readFactoryServiceUrl",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="factoryCode",value="设备所属厂商编号(后台给予)",required = true,dataType = "long",paramType="form"),
    })
    public R readFactoryServiceUrl(String factoryCode) {
        parameterIsBlank(factoryCode,"厂商编号不能为空");
        EstateEqFactory EqFactory=  estateEqFactoryService.selectOne(new EntityWrapper<EstateEqFactory>().eq("factory_code",factoryCode));
        parameterIsNull(EqFactory,"未查询到厂商信息");
        if(StringUtils.isBlank(EqFactory.getFactoryServiceUrl())){
            EqFactory.setFactoryServiceUrl("");
        }
        return R.ok().put("data",EqFactory.getFactoryServiceUrl()).putDescription("{data:厂商设备对应的服务地址(ip:port)},");
    }

    @ApiOperation(value = "查询我的开门信息")
    @RequestMapping(value = "/readMyOpenDoorInfo",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="memberId",value="会员id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="isReadByHouse",value="是(1)否(2-默认)根据当前户室查询",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="houseId",value="户室id",required = false,dataType = "long",paramType="form"),
    })
    public R readMyOpenDoorInfo(Long memberId,Integer isReadByHouse,Long houseId) {
        parameterIsNull(memberId,"会员信息不能为空");

        Wrapper<OwnerMember> omListWp = new EntityWrapper<OwnerMember>();
        omListWp.eq("member_id",memberId);
        if(isReadByHouse==null||isReadByHouse!=1){
            isReadByHouse = 2;
        }
        if(isReadByHouse==1){
            parameterIsNull(houseId,"户室信息不能为空");
            omListWp.eq("house_id",houseId);
        }
        omListWp.orderBy("agency_id",true);
        omListWp.orderBy("community_id",true);
        List<OwnerMember> omList = ownerMemberService.selectList(omListWp);
        if(omList==null){
            omList = new ArrayList<OwnerMember>();
        }
        List<Long> conmunityIdList = new ArrayList<Long>();
        List<Long> unitIdList = new ArrayList<Long>();
        List<Long> unit_conmunityIdList = new ArrayList<Long>();
        if(!omList.isEmpty()){
            for(int x=0;x<omList.size();x++){
                if(omList.get(x).getType()==3||omList.get(x).getType()==5){// 物业人员
                    if(!conmunityIdList.contains(omList.get(x).getCommunityId())){
                        conmunityIdList.add(omList.get(x).getCommunityId());
                    }
                }
            }
            for(int x=0;x<omList.size();x++){
                if(omList.get(x).getType()==1||omList.get(x).getType()==4){// 业主 + 家庭成员
                   if(!conmunityIdList.contains(omList.get(x).getCommunityId())){//过滤  物业人员 开所有门的
                       if(!unitIdList.contains(omList.get(x).getUnitId())){// 过滤 重复的单元
                           unitIdList.add(omList.get(x).getUnitId());
                           if(!unit_conmunityIdList.isEmpty()){//  过滤 查询小区大门  重复的 小区id
                               unit_conmunityIdList.add(omList.get(x).getCommunityId());
                           }
                       }
                   }
                }
            }
        }
        List<Map<String,Object>> doorLockInfoList = new ArrayList<Map<String,Object>>();
        if(!conmunityIdList.isEmpty()){//查询  物业人员
            Wrapper<EstateDoorLock> doorLockWp = new EntityWrapper<EstateDoorLock>();
            doorLockWp.in("conmunity_id",conmunityIdList);
            List<EstateDoorLock> doorLockList = estateDoorLockService.selectList(doorLockWp);
            doorLockInfoList.addAll(readLockInfo(doorLockList));
        }
        if(!unit_conmunityIdList.isEmpty()){// 查询 大门
            Wrapper<EstateDoorLock> doorLockWp = new EntityWrapper<EstateDoorLock>();
            doorLockWp.eq("door_type",1);
            doorLockWp.in("conmunity_id",unit_conmunityIdList);
            List<EstateDoorLock> doorLockList = estateDoorLockService.selectList(doorLockWp);
            doorLockInfoList.addAll(readLockInfo(doorLockList));
        }
        if(!unitIdList.isEmpty()){//查询 单元门
            Wrapper<EstateDoorLock> doorLockWp = new EntityWrapper<EstateDoorLock>();
            doorLockWp.in("unit_id",unitIdList);
            List<EstateDoorLock> doorLockList = estateDoorLockService.selectList(doorLockWp);
            doorLockInfoList.addAll(readLockInfo(doorLockList));
        }
        return R.ok().put("data",doorLockInfoList).putDescription(lockInfoDescription());
    }

    /**
     * 设备开门信息
     * @param list
     * @return
     */
    public List<Map<String,Object>> readLockInfo( List<EstateDoorLock> list){
        List<Map<String,Object>> lockInfoList = new ArrayList<Map<String, Object>>();
        if(list==null||list.isEmpty()){
            return lockInfoList;
        }
        List<EstateDoorLock> editList = new ArrayList<EstateDoorLock>();
        for(int x=0;x<list.size();x++){
            Map<String,Object> lockInfo = new HashMap<String,Object>();
            lockInfo.put("eqSn",list.get(x).getEqSn());
            lockInfo.put("eqMac",list.get(x).getEqMac());
            lockInfo.put("doorName",list.get(x).getDoorName());
            lockInfo.put("doorId",list.get(x).getDoorId());
            lockInfo.put("conmunityName",list.get(x).getConmunityName());
            lockInfo.put("conmunityId",list.get(x).getConmunityId());
            lockInfo.put("agencyId",list.get(x).getAgencyId());
            lockInfo.put("eqInputPswd",list.get(x).getEqInputPswd());
            if(null==lockInfo.get("eqInputPswd")){
                lockInfo.put("eqInputPswd","");
            }
            lockInfo.put("factoryCode",list.get(x).getFactoryCode());// 设备厂商id
            lockInfo.put("devType",list.get(x).getEqTypeFactory() );//厂商 提供的 设备类型
            if(null==lockInfo.get("devType")){
                lockInfo.put("devType","");//厂商 提供的 设备类型
            }
            if(list.get(x).getFactoryCode().equals("zhiGuo")){//智果锁
                if(StringUtils.isBlank(list.get(x).getEqPswd())){//密码过期
                    String url ="http://"+list.get(x).getFactoryServiceUrl()+"/dmserver/getUserEKey";
                    JSONObject params = new JSONObject();
                    params.put("devType", list.get(x).getEqTypeFactory());
                    params.put("devKey", list.get(x).getEqKey());
                    params.put("verified", 1);//有效期
                    params.put("startDate", "");
                    params.put("endDate", "");//有效期 永久
                    params.put("resSender", "");
                    JSONObject json = HttpClientUtil.doPost(url, params.toString());
                    if(json.getString("msg").equals("ok")){
                        lockInfo.put("eqPswd",json.getString("ekey") );//设备密码
                        list.get(x).setEqPswd(json.getString("ekey"));
                        editList.add(list.get(x));
                    }else{
                        logger.error(list.get(x).getConmunityName()+"的"+list.get(x).getDoorName()+"获取开门密码失败");
                        throw new RRException("获取开门密码失败",400);
                    }
                }
            }
            if(list.get(x).getFactoryCode().equals("daHao")){//大豪锁
                lockInfo.put("eqPswd",list.get(x).getEqKey() );//设备密码
            }
            lockInfoList.add(lockInfo);
        }
        if(!editList.isEmpty()){
            estateDoorLockService.updateBatchById(editList);
        }
        return lockInfoList;
    }

    /**
     * 开门信息描述
     * @return
     */
    public String lockInfoDescription() {
        StringBuilder descriptionStr = new StringBuilder("{");
        descriptionStr.append("eqSn:设备id(序列号),eqMac:设备mac地址,eqInputPswd:设备按键开门密码,eqPswd:设备密码,");
        descriptionStr.append("devType:厂商提供的参数-设备类型,");
        descriptionStr.append("conmunityName:社区名称,conmunityId:社区id,agencyId:物业机构id,");
        descriptionStr.append("doorName:门名称,conmunityId:门id,");
        descriptionStr.append("factoryCode:厂商编号(后台提供,eg:zhiGuo-智果，daHao-大豪),");
        descriptionStr.append("},");
        return descriptionStr.toString();
    }

    @ApiOperation(value = "远程开门")
    @RequestMapping(value = "/remoteOpenDoor",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="memberId",value="会员id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="doorId",value="门id",required = true,dataType = "long",paramType="form"),
    })
    public R remoteOpenDoor(Long memberId,Long doorId) {
        parameterIsNull(memberId,"会员id不能为空");
        parameterIsNull(doorId,"门id不能为空");
        EstateDoorLock doorLock = estateDoorLockService.selectOne(new EntityWrapper<EstateDoorLock>().eq("door_id",doorId));
        parameterIsNull(doorLock,"门尚未绑定锁设备");
        boolean edistDoorLockTag = false;
        if(doorLock.getDoorType()==null){
           EntranceDoor door = entranceDoorService.selectById(doorId);
           parameterIsNull(doorLock,"未查询到门信息");
           if(door.getDoorType()==null){
               return R.error(400,"门信息出错");
           }
           doorLock.setDoorType(door.getDoorType());
            edistDoorLockTag = true;
        }
        int countMemberHouse = 0;
        Wrapper<OwnerMember> countMemberHouseWp = new EntityWrapper<OwnerMember>();
        countMemberHouseWp.eq("member_id",memberId);
        if(doorLock.getDoorType()==1){
            countMemberHouseWp.eq("community_id",doorLock.getConmunityId());
            countMemberHouseWp.and("type_ <> {0}",2);
        }else{
            countMemberHouseWp.eq("unit_id",doorLock.getUnitId());
        }
        countMemberHouse = ownerMemberService.selectCount(countMemberHouseWp);
        if(countMemberHouse<1){
            return R.error(400,"请您先认证房屋后再执行该操作!");
        }
        if(doorLock.getFactoryCode().equals("zhiGuo")){// 智果
            //远程开门请求地址
            String url = "http://"+doorLock.getFactoryServiceUrl()+"/dmserver/controlDevice";
            JSONObject params = new JSONObject();
            params.put("operate", 1); //操作方式 远程开门
            JSONObject params2 = new JSONObject();
            params2.put("devSn", doorLock.getEqSn());
            params2.put("doorNo", 1);//开启第几个门
            params.put("data", params2);
            JSONObject json = HttpClientUtil.doPost(url, params+"");
            if(!json.getString("msg").equals("ok")){
               return R.error(400,"远程开门失败!");
            }
        }
        if(doorLock.getFactoryCode().equals("daHao")){// 大豪
            JSONObject resultJson = null;
            StringBuilder url = new StringBuilder("http://").append(doorLock.getFactoryServiceUrl())
                    .append(daHaoLockUtil.readDaHaoServiceWarName()).append("/app/openRemoteDeviceLock")
                    .append("?DEVICE_ID=").append(doorLock.getEqSn())
                    .append("&DEVICEPSW=").append(doorLock.getEqPswd());
            resultJson = HttpClientUtil.doPost(url.toString(), "");
            int resultCode = resultJson.getIntValue("result");
            switch(resultCode){
                case 0:return R.ok("本次开门成功");
                case 203:return R.error(400,"设备不在线，请联系物业管理员");
                case 201:return R.error(400,"设备不在线，请联系物业管理员");
                default:return R.error("本次开门失败");
            }
        }
        return R.ok();
    }

    @ApiOperation(value = "获取临时开门密码")
    @RequestMapping(value = "/readTempPswd",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="memberId",value="会员id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="doorId",value="门id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="pswdType",value="密码类型(1-数字,2-二维码)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="endTime",value="密码有效期",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="visitorPhone",value="访客电话",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="visitorName",value="访客姓名",required = false,dataType = "String",paramType="form"),
    })
    public R readTempPswd(Long memberId,Long doorId,Integer pswdType,String endTime,String visitorPhone,String visitorName) {
        parameterIsNull(memberId,"会员id不能为空");
        parameterIsNull(doorId,"门id不能为空");
        if(pswdType==null||pswdType!=2){
            pswdType = 1;
        }
        EstateDoorLock doorLock = estateDoorLockService.selectOne(new EntityWrapper<EstateDoorLock>().eq("door_id",doorId));
        parameterIsNull(doorLock,"门尚未绑定锁设备");
        Date dateTime = new Date();//当前时间
        Date paramDateTime = null;
        if(StringUtils.isNotBlank(endTime)){
            try {
                paramDateTime= new SimpleDateFormat("yyyyMMddHHmm").parse(endTime);
            } catch (ParseException e) {
                paramDateTime =  DateUtil.addDate(dateTime, 5, 1);//当前时间加一天
            }
            dateTime = DateUtil.addDate(dateTime, 12, 30);//当前时间增加30分钟
            if(paramDateTime.getTime()<=dateTime.getTime()){//判断有效期时间是否在半个小时以上
                paramDateTime =  DateUtil.addDate(new Date(), 5, 1);//当前时间加一天
            }
            dateTime = DateUtil.addDate(new Date(), 5, 6);//当前时间增加7天
            if(paramDateTime.getTime()>dateTime.getTime()){
                paramDateTime = dateTime;//当前时间加六天
            }
        }
        if(paramDateTime==null){
            paramDateTime = DateUtil.addDate(dateTime, 5, 1);//当前时间加一天
        }
        String time =DateUtil.format(paramDateTime, DateUtil.DATE_PATTERN.YYYYMMDDHHMMSS);
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("remark", "密码开门规则：先按*,键输入密码结束按#键！");
        returnMap.put("pswd", "");
        if(doorLock.getFactoryCode().equals("zhiGuo")){//智果
            String url = "http://"+doorLock.getFactoryServiceUrl()+"/dmserver/getTempPwd";
            JSONObject params = new JSONObject();
            params.put("devKey",doorLock.getEqPswd());
            params.put("endDate", time);//密码有效期
            params.put("pwdType", pswdType);//面方式 1 密码 2二维码
            JSONObject json = HttpClientUtil.doPost(url, params+"");
            if(json.getString("msg").equals("ok")){
                if(pswdType==1){
                    returnMap.put("pswd", json.get("pwd"));
                }else{
                    returnMap.put("pswd", json.get("qrcodeImg"));
                }
                returnMap.put("remark", "密码开门规则：先按*,键输入密码结束按#键！");
            }else{
                return R.error(400,"获取临时密码失败");
            }
        }
        if(doorLock.getFactoryCode().equals("daHao")){//大豪
            returnMap.put("pswd",doorLock.getEqInputPswd() );
            if(null==returnMap.get("pswd")){
                returnMap.put("pswd",12345678 );
            }
        }
        /**
         * 添加访客记录
         */
//      cisitorRecordService.saveVisitorRecord(memberId, name, phone);
        return R.ok().put("data",returnMap);
    }

    @ApiOperation(value = "获取访客邀请参数-大豪设备")
    @RequestMapping(value = "/readInvitedVisitorParam",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="memberId",value="会员id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="houseId",value="当前户室id",required = true,dataType = "long",paramType="form"),
    })
    public R readInvitedVisitorParam(Long memberId,Long houseId) {
        parameterIsNull(memberId,"会员id不能为空");
        parameterIsNull(houseId,"当前户室id不能为空");
        OwnerMember om = ownerMemberService.selectOne(new EntityWrapper<OwnerMember>().eq("member_id",memberId).eq("house_id",houseId));
        parameterIsNull(om,"您没有权限，请先认证房屋");
        if(om.getType()==3||om.getType()==5){
            return R.error(400,"物业办公室不能邀请访客");
        }
        Wrapper<EstateDoorLock> doorLockWp=new EntityWrapper<EstateDoorLock>().eq("conmunity_id",om.getCommunityId());
        doorLockWp.eq("unit_id",om.getUnitId());
        List<EstateDoorLock> doorLockList = estateDoorLockService.selectList(doorLockWp);
        if(doorLockList==null||doorLockList.isEmpty()){
            return R.error(400,"该单元的单元门尚未绑定设备，请联系物业管理员");
        }
        UnitBuilding unit =unitBuildingService.selectById(om.getUnitId());
        parameterIsNull(unit,"未查询到户室所属单元信息");
        List<Map<String,Object>> mapList = new ArrayList<Map<String, Object>>();
        for(int x=0;x<doorLockList.size();x++){
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("unitNum",unit.getUnitNum());
            map.put("communityNum",unit.getCommunityNum());
            map.put("doorId",doorLockList.get(x).getDoorId());
            map.put("doorName",doorLockList.get(x).getDoorName());
            map.put("eqSn",doorLockList.get(x).getEqSn());
            map.put("eqPswd",doorLockList.get(x).getEqPswd());
            mapList.add(map);
        }
        return R.ok().put("data",mapList).putDescription(getInvitedVisitorParamDesc());
    }

    public String getInvitedVisitorParamDesc(){
        StringBuilder str = new StringBuilder("{");
        str.append("unitNum:单元编号,communityNum:小区编号,");
        str.append("doorId:门id,doorName:门名称,");
        str.append("eqSn:设备id,eqPswd:设备密码,");
        str.append("},");
        return str.toString();
    }
}
